#include "mem_user_storage.hpp"

namespace storage {

MemUserStorage::MemUserStorage() {
    // 初始化内存数据库
    users_ = std::unordered_map<std::string, UserEntity>();
    sessions_ = std::unordered_map<std::string, UserSession>();
}

bool MemUserStorage::create_user(const UserEntity& user) {
    users_[user.username] = user;
    return true;
}

std::optional<UserEntity> MemUserStorage::get_user_by_username(const std::string& username) {
    auto it = users_.find(username);
    if (it != users_.end()) {
        return it->second;
    }
    return std::nullopt;
}

std::optional<UserEntity> MemUserStorage::get_user_by_id(int64_t user_id) {
    for (const auto& [username, user] : users_) {
        if (user.id == user_id) {
            return user;
        }
    }
    return std::nullopt;
}

bool MemUserStorage::update_user(const UserEntity& user) {
    users_[user.username] = user;
    return true;
}

bool MemUserStorage::delete_user(int64_t user_id) { 
    for (auto it = users_.begin(); it != users_.end(); ++it) {
        if (it->second.id == user_id) {
            users_.erase(it);
            return true;
        }
    }
    return false;
}

bool MemUserStorage::exists_by_username(const std::string& username) {
    return users_.find(username) != users_.end();
}

bool MemUserStorage::store_session(const UserSession& session) {
    sessions_[session.username] = session;
    return true;
}

bool MemUserStorage::delete_session(const std::string& username) {
    sessions_.erase(username);
    return true;
}

std::optional<UserSession> MemUserStorage::get_session(const std::string& username) {   
    auto it = sessions_.find(username);
    if (it != sessions_.end()) {
        return it->second;
    }
    return std::nullopt;
}   
} // namespace storage